package cn.maydaymemory.mastery.command.api;

import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.Configuration;

import java.util.ArrayList;
import java.util.List;

public class SuperCommand extends Command {
    private CommandStructureExecutor executor;
    public SuperCommand(String name, CommandStructure structure,Configuration language){
        super(name);
        changeStructure(structure,language);
    }
    public SuperCommand(String name, CommandStructure structure){
        super(name);
        changeStructure(structure);
    }
    @Override
    public boolean execute(CommandSender sender, String label, String[] args) {
        executor.sender(sender);
        //执行命令
        if(args.length<1&&executor.helperEnable()){
            executor.sendHelp(1);
            return true;
        }
        for(int f =0;f<args.length;f++){
            args[f] = args[f].replaceAll("&","§");
        }
        if(args.length==1){
            executor.excute(args[0],label,new String[0]);
            return true;
        }
        if(args.length>1){
            String[] par = new String[args.length - 1];
            System.arraycopy(args, 1, par, 0, args.length - 1);
            executor.excute(args[0],label,par);
            return true;
        }
        return true;
    }
    public SuperCommand changeStructure(CommandStructure structure,Configuration language){
        executor=new CommandStructureExecutor(structure,language);
        executor.structure().changeHelperTitle("§7"+this.getName()+"'s help");
        return this;
    }
    public SuperCommand changeStructure(CommandStructure structure){
        executor=new CommandStructureExecutor(structure);
        executor.structure().changeHelperTitle("§7"+this.getName()+"'s help");
        return this;
    }
    public CommandStructureExecutor executor(){ return executor;}

    public SuperCommand language(Configuration language){
        executor.language(language);
        return this;
    }
    public Configuration language(){
        return executor.language();
    }
    @Override
    public List<String> tabComplete(CommandSender sender, String alias, String[] args) {
        CommandStructureExecutor executor = this.executor;
        if(args[0].equals("")){
            return executor.structure().complete();
        }
        boolean find = false;
            for(String arg : args){
                CommandStructure structure =executor.getChildStructure(arg);
                if(structure!=null){
                    executor = executor.structure().getChildStructureExecutor(structure);
                    find=true;
                }
            }
        if (find)
            return executor.structure().complete();
        else return new ArrayList<>();
    }
}
